<template>
  <div class="player-lyric">
    <slot></slot>
    <div class="player-lyric__content" ref="content">
      <scroll :data='lines' ref="scroll">
        <ul>
          <li v-for="(line, index) of lines"
              :key="index"
              :class="curNum === index ? 'active' : ''"
              :ref="'item-' + index"
              :data-index="index"
          >
            {{ line.txt }}
          </li>
        </ul>
      </scroll>
    </div>
  </div>
</template>

<script>
import { mapActions, mapGetters } from 'vuex'
import Lyric from '@/entity/Lyric'
import scroll from 'base/scroll'

const ITEM_HEIGHT = 30

export default {
  components: {
    scroll
  },
  props: {
    currentTime: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      lyric: null,
      lines: [],
      curNum: 0
    }
  },
  computed: {
    ...mapGetters('player', ['currentSong'])
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      this.lines = []
      this.curNum = 0
      if (this.lyric) {
        this.lyric.stop()
      }
      setTimeout(() => {
        this.getLyric()
      })
    },
    async getLyric() {
      let lyric = await this.currentSong.getLyric()
      this.lyric = new Lyric(lyric, this.handel)
      this.lines = this.lyric.lines
      if (this.lines.length) {
        this.$nextTick(() => {
          const padding = this.$refs.content.clientHeight / 2 - ITEM_HEIGHT / 2
          this.$refs[`item-${0}`][0].style['padding-top'] = `${padding}px`
          this.$refs[`item-${this.lines.length - 1}`][0].style['padding-bottom'] = `${padding}px`
          this.$refs.scroll.refresh()
        })
      }
      this.lyric.play()
    },
    togglePlay() {
      this.lyric.togglePlay()
    },
    seek(offset) {
      this.lyric.seek(offset)
    },
    handel({ lineNum, txt }) {
      this.curNum = lineNum
      this.scrollTo(-lineNum * ITEM_HEIGHT)
    },
    scrollTo(y) {
      this.$refs.scroll && this.$refs.scroll.scrollTo(0, y, 400)
    },
    refresh() {
      this.$refs.scroll.refresh()
    }
  },
  watch: {
    currentSong(newSong, oldSong) {
      if (!newSong) {
        return
      }
      if (oldSong && newSong.id === oldSong.id) {
        return
      }
      this.init()
      this.scrollTo(0)
    }
  }
}
</script>

<style lang="less" scoped>
@import '~@/style/variable.less';

.player-lyric{
  height: 100%;
  .player-lyric__content{
    position: relative;
    height: 100%;
    overflow: hidden;
    text-align: center;
    li{
      color: hsla(0,0%,100%,.5);
      height: 30px;
      line-height: 30px;
    }
    .active{
      color: white;
    }
  }
}
</style>